package com.jy.service.impl;

import com.jy.common.UUIDUtils;
import com.jy.dao.CopeCreditDao;
import com.jy.dao.MoneyManageDao;
import com.jy.model.*;
import com.jy.service.AppBaseService;
import com.jy.service.MoneyManageService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Serivce实现类
 * Tue May 09 15:12:04 GMT+08:00 2017 zzp
 */


@Component
public class MoneyManageServiceImpl implements MoneyManageService {
    @Resource
    private MoneyManageDao moneyManageDao;
    @Resource
    private AppBaseService appBaseService;
    @Resource
    private CopeCreditDao cpd;
    public boolean insertMoneyApply(MoneyManage mm, String realname, String dbUser) {
        // TODO Auto-generated method stub
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//当前时间
        String apply_time=dateFormat.format(now);
        mm.setApply_time(apply_time);
        ProcessInstance processInstance = appBaseService.startProcessInstance(
                "inputUser", mm.getApply_man(), "MoneyManage",
                mm.getId());
        if (processInstance != null) {
            System.out.println("启动请假单流程成功");
        }
        Department dept = new Department();
        if(mm.getDeptId()!=null && !mm.getDeptId().equals("")){
            dept=cpd.searchdept(mm.getDeptId());
        }else{
            dept.setDepartment_name("");
        }
        if(mm.getTypes().equals("0")){
            mm.setBh("SCF-YSZK"+mm.getBh());
            mm.setProject_name(dept.getDepartment_name()+"应收账款债权转让");
        }else if(mm.getTypes().equals("1")){
            mm.setBh(mm.getBh());
        }else if(mm.getTypes().equals("2")){
            mm.setBh("SCF-XYRZ"+mm.getBh());
            mm.setProject_name(dept.getDepartment_name()+"信用融资");
        }
        // 讲流程ID放入自定义表单中
        mm.setProcessId(processInstance.getId());
        int a = moneyManageDao.insertMoneyApply(mm);
        // 获取任务id
        String taskId = moneyManageDao.getTaskId(processInstance.getId());
        // 修改历史任务里的owner改为当前用户
        int b = moneyManageDao.updateOwner(realname, taskId);
        //发起流程

        Map<String, Object> variables = new HashMap<String, Object>();
        if (mm.getTypes().equals("0") || mm.getTypes().equals("2")) {
            variables.put("message", "事业部");
        } else {
            variables.put("message", "行业中心");
        }
        variables.put("nextUser", dbUser);
        this.updateState(processInstance.getId(), variables, mm.getId(), dbUser, dbUser,mm.getApply_time(),realname);

        //	boolean flag2=mmService.updateState(processInstance.getId(),variables, mm.getId(), dbUser, dbUser);
        return a > 0 && b > 0;

    }

    @Override
    public List<User> getUsers(String name) {
        return moneyManageDao.getUsers(name);
    }

    @Override
    public List<MoneyManage> moneyList(Integer rows, Integer page, String token,String project_name) {
        return moneyManageDao.moneyList(rows,page,token,project_name);
    }

    @Override
    public MoneyManage getsingMoneyApplyInfo(String id) {
        return moneyManageDao.getsingMoneyApplyInfo(id);
    }

    @Override
    public List<Comment> getComment(String processId) {
        return moneyManageDao.getComment(processId);
    }

    @Override
    public List<MoneyManage> getTaskMoney(Integer state, Integer size, String token) {
        return moneyManageDao.getTaskMoney(state,size,token);
    }
    public  int getTaskMoneyCount(String token){
        return moneyManageDao.getTaskMoneyCount(token);
    }

    @Override
    public List<String> getTaskPvm(String taskid) {
        return appBaseService.getTaskPvm(taskid);
    }

    @Override
    public MoneyManage getsingTaskMoney(String id) {
        return moneyManageDao.getsingTaskMoney(id);
    }

    @Override
    public int updateSHR(MoneyManage mm) {
        return moneyManageDao.updateSHR(mm);
    }

    @Override
    public int updateJiafang(String jopen_bank, String jaccount_name, String jaccount_number, String id) {
        return moneyManageDao.updateJiafang(jopen_bank,jaccount_name,jaccount_number,id);
    }

    @Override
    public int updateStatus(String id, int status) {
        return moneyManageDao.updateStatus(id, status);
    }

    @Override
    public int updatePass(String userId,String pocessId, Map<String, Object> variables, String commons, String id, String tjuser, String btnName, String realname) {

        // TODO Auto-generated method stub
        System.out.println(commons);
        ProcessInstance pi = appBaseService.applyComplete(pocessId, variables,
                commons, tjuser, btnName);
        // 获取任务id
        String taskId =moneyManageDao.getTaskId(pocessId);

        // 修改历史任务里的owner改为当前用户
        int b =moneyManageDao.updateOwner(realname, taskId);

        if(btnName.equals("通过")){
            moneyManageDao.updateStatus(taskId, 1);

        }
        String cl_times=moneyManageDao.maxCreateTime(id);
        MoneyGuiJi og = liuchengguiji(id,userId,pocessId, commons,
                cl_times, btnName);
        int fag = 0;
        if (pi == null) {
            System.out.println(id+"================================");
            moneyManageDao.updateLiuChengApplyStatus(og.getId());
            fag =moneyManageDao.updateStatus(id, 2);

        }
        //审核更改撤销状态
        moneyManageDao.updateStatus2(id,"1");
        return fag;
    }

    @Override
    public List<MoneyManage> guiJiList(Integer state, Integer size, String token) {
        return moneyManageDao.guiJiList(state,size,token);
    }

    @Override
    public MoneyManage getsingGuiJi(String id) {
        return moneyManageDao.getsingGuiJi(id);
    }


    /**
     * @param id
     * @return 请假发起---提交请假申请 将状态改为1（审核中） pocessId 流程实例id id 主键id dbUser 下一执行人
     *
     */
    public boolean updateState(String pocessId,Map<String, Object> variables, String id,
                               String dbUser, String realname,String cl_time,String realname2) {
        // 结束当前任务进入下一任务，并指定下一执行人（给nextUser赋值为dbUser）；如果流程实例为空则流程实例结束，否则没有结束
        ProcessInstance pi = appBaseService.applyComplete(pocessId, variables);
        int a =moneyManageDao.updateStatus(id, 1);
        int a2 =moneyManageDao.updateStatus2(id, "0");
        // 获取任务id
        String taskId = moneyManageDao.getTaskId(pocessId);
        // 修改历史任务里的owner改为当前用户
        int b = moneyManageDao.updateOwner(realname, taskId);


        //流程轨迹中增加记录

        String cl_times=moneyManageDao.maxCreateTime(id);
        String btnName="提交申请";
        //如果有最大时间，把最大时间赋给操作时间，如果没有，把记录的创建时间赋给操作时间
        if(cl_times!=null) {
            MoneyGuiJi og = liuchengguiji(id, realname2, pocessId, null,
                    cl_times, btnName);
        }else{
            MoneyGuiJi og = liuchengguiji(id, realname2, pocessId, null,
                    cl_time, btnName);
        }
        return a > 0 && b > 0;
    }

    public List<Comment> getCommentInfo(String processId){
        return moneyManageDao.getCommentInfo(processId);
    }



    private MoneyGuiJi liuchengguiji(String id, String userId, String process_id, String commons, String cl_time, String btnName) {

        //String dbUser = (String) variables.get("nextUser");
         String deptIds  = moneyManageDao.searchDepartmentId(userId);//根据员工ID得到部门ID，用于权限控制
        /**
         * 添加历史表数据
         * 流程审核轨迹
         */
        MoneyGuiJi mg = new MoneyGuiJi();
        mg.setId(UUIDUtils.getUUID());//流程轨迹Id
        mg.setProcess_id(process_id);//流程ID
        mg.setDepartment_id(deptIds);//审核人所在部门ID
        mg.setUser_id(userId);//审核人用户ＩＤ
        //根据员工id，得到员工的权限
        List<MoneyGuiJi> mgj = moneyManageDao.searchRoleName(userId);
        String str="";
        for(MoneyGuiJi mgs:mgj){
            System.out.print(mgs.getRoleName());
            str=mgs.getRoleName()+","+str;
        }
        mg.setRoleid(str);//权限名称
        mg.setRealName(mgj.get(0).getRealName());
        mg.setDeptName(mgj.get(0).getDeptName()+"--"+mgj.get(0).getDeptName1()+"--"+mgj.get(0).getDeptName2());

        mg.setCl_time(cl_time);//操作时间
        mg.setComment(commons);//审核意见
        mg.setMoneyId(id);

        if(btnName.equals("驳回")){
            mg.setApply_status(1);//0:转到下一人 1:驳回
            mg.setStatus(1);//0:是  1：否
        }else if(btnName.equals("通过")){
            mg.setApply_status(0);//0:转到下一人
            mg.setStatus(0);//0:是  1：否
        }else if(btnName.equals("提交申请")){
            mg.setApply_status(3);//提交申请
            mg.setStatus(0);//0:是  1：否
        }else if(btnName.equals("撤销")){
            mg.setApply_status(4);//撤销
            mg.setStatus(0);//0:是  1：否
        }
        moneyManageDao.insertMoneyGuiJi(mg);//保存轨迹
        return mg;
    }


//轨迹明细列表
   public List<MoneyGuiJi> getLiuChengGuiJi(Integer rows, Integer page,String proId){
        return moneyManageDao.getLiuChengGuiJi(rows,page,proId);
    }

    //保存文件
    public int saveFilename(List<MoneyFile> list){
        return moneyManageDao.saveFilename(list);
    }

    //获取用户权限
    public Integer[] getUserRote(String id, String custormer){
        return moneyManageDao.getUserRote(id,custormer);
    }

    /**
     * 查看图片
     */
    public List <MoneyFile>getImgS(String moneyId){

            return moneyManageDao.getImgS(moneyId);
    }

    /**
     * 撤销流程
     * @param id
     * @param process_id
     * @return
     */
    public int iscx(String id, String process_id,String realname,String userId) {
        appBaseService.deleteProcessInstance(process_id, "");
        moneyManageDao.updateExecution(process_id,id+"-"+process_id);
        ProcessInstance processInstance =appBaseService.startProcessInstance("inputUser",realname, "MoneyManage",id);
        process_id=processInstance.getId();
        MoneyManage mm = moneyManageDao.searchId(id);
        String iscx="1";
        String aduit_state="0";
        int i=moneyManageDao.updateCXLC(id,processInstance.getId(),iscx,aduit_state);
        String btnName="撤销";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String time = df.format(new Date());
        liuchengguiji(id,userId,process_id,"",time,btnName);

        return i;
    }


    /**
     * 合同编号去重
     * @param mm
     * @return
     */
    public List<MoneyManage> searchApply(MoneyManage mm) {
        // TODO Auto-generated method stub
        return moneyManageDao.searchApply(mm);
    }

}








